package com.ybox.common.core.utils;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ych
 */
public class UrlSpiltUtils {


    /**
     * 将url中参数封装成map
     *
     * @param url
     * @return
     */
    public static Map<String, String> getUrlMap(String url) {
        Map<String, String> map = new HashMap<String, String>();
        URL urls = null;
        try {
            urls = new URL(url);

        } catch (MalformedURLException e) {
            try {
                urls = new URL("http:"+url);
            } catch (MalformedURLException ex) {
                throw new RuntimeException(ex);
            }
        }
        String param = urls.getQuery();
        if (StringUtils.isNotBlank(param)) {
            String[] arr = param.split("&");
            for (String s : arr) {
                String key = s.split("=")[0];
                String value = s.split("=")[1];
                map.put(key, value);
            }
        }
        return map;
    }

    /**
     * hashMap 转化成表单字符串
     *
     * @param map
     * @return
     */
    public static String map2Form(Map<String, String> map) {
        StringBuilder stringBuilder = new StringBuilder();
        if (map == null || map.size() == 0) {
            return stringBuilder.toString();
        } else {
            for (Map.Entry<String, String> entry : map.entrySet()) {
                stringBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
            return stringBuilder.substring(0, stringBuilder.length() - 1);
        }
    }


    /**
     * 表单字符串转化成 hashMap
     *
     * @param orderinfo
     * @return
     */
    public static HashMap<String, String> form2Map(String orderinfo) {
        String listinfo[];
        HashMap<String, String> map = new HashMap<String, String>();
        listinfo = orderinfo.split("&");
        for (String s : listinfo) {
            String list[] = s.split("=");
            if (list.length > 1) {
                map.put(list[0], list[1]);
            }
        }
        return map;
    }

    public static void main(String[] args) {
        Map<String, String> urlMap = getUrlMap("user?page=1&size=2");
        System.out.println(urlMap);
    }

}